<?php
/*
 * TODO метод Get - зачем здесь?
 * Создать модель на каждую таблицу, для начала на sections
 * перенести метод getSections в нее
 *
 * Забрать отсюда getSectionIdByName()
 * В виджет придется передвать modul_id
 */
class Model extends controllerInterface{

    public $registry;
    //public $virtual_modul_index;
    //public $modul_index ;
    public $unit ;

    public $index = 0;
    public $stop_xml_forming = false;

    private $ftpConnection = null;

    function __construct(){
       
        $this->registry = Registry::getInstance();

        // [!] не работает, т.к. на этапе запуска модели эти параметры не определены
        //$this->virtual_modul_index = mb_strtolower($this->registry->virtual_modul_index);
        //$this->modul_index = mb_strtolower($this->registry->modul_index);
       
    } // -- __construct
    
    /*
    function Get($tpl){
    // returns an Output (html) to put it into var (brutal fetching)
    
        ob_start();
        $this->smarty->display($tpl);        
        $html = ob_get_clean();
        return $html;
    } // -- Get()
  
    function Set($tpl_var, $var){
    // interface for assign()
        $this->smarty->assign($tpl_var, $var);
        
    } // -- Set()
    */

    // TODO этот метод лучше поместить в библиотечный класс
    function imgCropAndResize($old_name, $new_name, $width = 0, $height = 0){   
    //!!! Новый всеядный метод для создания thumbnailов строго фиксированной ширины
    //и высоты из фоток
    //Если ширина или высота не задана (равна нулю), то фотка не обрезается,
    //а просто недостающий параметр высчитывается пропорционально
    // -100 Разрешение больше допустимого

    //Если заданы неверные параметры
    if($width <= 0 && $height <= 0) return false;
   
    if(!is_file($old_name)) return -1;
   
    /*
      $path_info = pathinfo($_FILES["img"]['name']);
            $ext = $path_info['extension'];
   
  
    $ext_is_allowed = false;
    if($ext == 'jpg')  $ext_is_allowed = true;
    if($ext == 'jpeg')  $ext_is_allowed = true;
    if($ext == 'png')  $ext_is_allowed = true;
    if($ext == 'gif')  $ext_is_allowed = true;  
    if(!$ext_is_allowed)  
      return -101;
      
    $filesize =  $_FILES["userfile_$file_index"]['size']; 
    if($filesize > 2048000)  
      return -102;

      // --
       // проверить картинку
        $path_info = pathinfo($_FILES["img"]['name']);
        $ext = $path_info['extension'];
      
        
        if($ext == 'jpg' OR $ext == 'jpeg' OR $ext == 'png' OR $ext == 'gif'){}
        else
          return   $this->Msg('Допустимые расширени графических файлов: jpg, jpeg, png, gif', '/events/', 1000);
          
        $filesize =  $_FILES["img"]['size']; 
        if($filesize > 2048000)  
          return $this->Msg('Допустимый размер файла: 2МБ', '/events/', 1000);   
          
        $size = GetImageSize($_FILES['img']['tmp_name']);            
        if($size[0] > 3000 OR $size[1] > 3000) 
           return $this->Msg('Допустимое разрешение 3000 х 3000 пикселей', '/events/', 1000);   
      
      */
   // пример
   /*
      fb($size[0]); 3264
      fb($size[1]); 2448
      fb($old_name); // /tmp/phpDzbhS6
   */
     
   
    //Определяем размер фотографии
    $size=GetImageSize ($old_name);

    $limit_resolution = 4000;
  

    if($size[0] > $limit_resolution OR $size[1] > $limit_resolution) return -100;
    
    //Создаём новое изображение из «старого»
    //определяем тип файла по содержимому
    if ($size['mime'] == "image/gif")  $src = imagecreatefromgif($old_name);
    if ($size['mime'] == "image/jpeg") $src = imagecreatefromjpeg($old_name);
    if ($size['mime'] == "image/png")  $src = imagecreatefrompng($old_name);
    if (!$src) return false;

    //Вычисляем ширину/высоту
    $iw=$size[0];
    $ih=$size[1];
    
    //Если всё больше нуля то создаем новую фотку с обрезкой
    if($width > 0 && $height > 0)
    $dst=ImageCreateTrueColor ($width, $height);
    
    //Если один из параметров == 0, то без обрезки
    //Недостающий параметр высчитывается пропорцией
    if($width == 0){
        $width = $iw*$height/$ih;
        $dst=ImageCreateTrueColor ($width, $height);
    }
    if($height == 0){
        $height = $ih*$width/$iw;
        $dst=ImageCreateTrueColor ($width, $height);
    }
    
    //Если высота исходной фотки > ширины
    if($ih > $iw){
        //вычисляем коэфициент 
        //соотношения ширины оригинала с будущей превьюшкой.
        $koe=$iw/$width;
        //Делим высоту изображения на коэфициент, полученный в предыдущей строке, 
        //и округляем число до целого в большую сторону — в результате получаем 
        //высоту нового изображения.
        $new_h=ceil ($ih/$koe);
     
        //Вычисляем, какую высоту должна была бы иметь исходная фотка чтоб 
        //попадать в наши пропорции (120х160 например для событий)
        $tmp = ceil($iw*$height/$width);
        
        //Если получается что эта "идеальная" высота больше реальной
        //обрезаем фотку по бокам, выравниванием по центру по горизонтали.
        
        if($tmp > $ih){
            $koe=$ih/$height;
            $new_w=ceil ($iw/$koe);
            
            //Теперь уже вычисляем "идеальную" ширину
            $tmp = ceil($ih*$width/$height);
            $shift_x = ceil($iw/2 - $tmp/2);

            ImageCopyResampled ($dst, $src, 0, 0, $shift_x, 0, $new_w, $height, $iw, $ih);    
        }
        //Иначе обрезаем фотку сверху и снизу, выравниванием по центру по вертикали.
        else{
            $shift_y = ceil($ih/2 - $tmp/2);

            ImageCopyResampled ($dst, $src, 0, 0, 0, $shift_y, $width, $new_h, $iw, $ih);
        }
    }
    
    //Если высота исходной фотки < ширины
    else{
        $koe=$ih/$height;
        $new_w=ceil ($iw/$koe);
        
        $tmp = ceil($ih*$width/$height);
        
        if($tmp > $iw){


            $koe=$iw/$width;
            $new_h=ceil ($ih/$koe);
            
            //Теперь уже вычисляем "идеальную" ширину
            $tmp = ceil($iw*$height/$width);
            $shift_y = ceil($ih/2 - $tmp/2);

            /*$result = */ ImageCopyResampled ($dst, $src, 0, 0, 0, $shift_y, $width, $new_h, $iw, $ih);
        }
        else{
        
            $shift_x = ceil($iw/2 - $tmp/2);

            ImageCopyResampled ($dst, $src, 0, 0, $shift_x, 0, $new_w, $height, $iw, $ih);
        }
    }
    //Сохраняем полученное изображение в формате JPG
    ImageJPEG ($dst, $new_name, 100); 
 }
    
  function translitEncodedURL($st){
      $lit = array(
      "%D0%B0" => "a", 
      "%D0%B1" => "b", 
      "%D0%B2" => "v", 
      "%D0%B3" => "g", 
      "%D0%B4" => "d", 
      "%D0%B5" => "e", 
      "%D1%91" => "jo", 
      "%D0%B6" => "zh", 
      "%D0%B7" => "z", 
      "%D0%B8" => "i",  
      "%D0%B9" => "ij",   
      "%D0%BA" => "k", 
      "%D0%BB" => "l", 
      "%D0%BC" => "m", 
      "%D0%BD" => "n", 
      "%D0%BE" => "o", 
      "%D0%BF" => "p", 
      "%D1%80" => "r", 
      "%D1%81" => "s", 
      "%D1%82" => "t", 
      "%D1%83" => "u", 
      "%D1%84" => "f", 
      "%D1%85" => "h", 
      "%D1%86" => "z", 
      "%D1%87" => "ch", 
      "%D1%88" => "sh",
      "%D1%89" => "shch",
      "%D1%8A" => "",
      "%D1%8B" => "y",
      "%D1%8C" => "",
      "%D1%8D" => "e",
      "%D1%8E" => "ju",
      "%D1%8F" => "ja"
      );
    
      return $st = strtr($st, $lit);
  } // -- 

  function translitBackToCyr($st){
      $lit = array(
      "%D0%B0" => "а", 
      "%D0%B1" => "б", 
      "%D0%B2" => "в", 
      "%D0%B3" => "г", 
      "%D0%B4" => "д", 
      "%D0%B5" => "е", 
      "%D1%91" => "ё", 
      "%D0%B6" => "ж", 
      "%D0%B7" => "з", 
      "%D0%B8" => "и",  
      "%D0%B9" => "й",   
      "%D0%BA" => "к", 
      "%D0%BB" => "л", 
      "%D0%BC" => "м", 
      "%D0%BD" => "н", 
      "%D0%BE" => "о", 
      "%D0%BF" => "п", 
      "%D1%80" => "р", 
      "%D1%81" => "с", 
      "%D1%82" => "т", 
      "%D1%83" => "у", 
      "%D1%84" => "ф", 
      "%D1%85" => "х", 
      "%D1%86" => "ц", 
      "%D1%87" => "ч", 
      "%D1%88" => "ш",
      "%D1%89" => "щ",
      "%D1%8A" => "ъ",
      "%D1%8B" => "ы",
      "%D1%8C" => "ь",
      "%D1%8D" => "э",
      "%D1%8E" => "ю",
      "%D1%8F" => "я",

      "%D0%90" => "А",
      "%D0%91" => "Б",
      "%D0%92" => "В",
      "%D0%93" => "Г",
      "%D0%94" => "Д",
      "%D0%95" => "Е",
      "%D0%81" => "Ё",
      "%D0%96" => "Ж",
      "%D0%97" => "З",
      "%D0%98" => "И",
      "%D0%99" => "Й",
      "%D0%9A" => "К",
      "%D0%9B" => "Л",
      "%D0%9C" => "М",
      "%D0%9D" => "Н",
      "%D0%9E" => "О",
      "%D0%9F" => "П",
      "%D0%A0" => "Р",
      "%D0%A1" => "С",
      "%D0%A2" => "Т",
      "%D0%A3" => "У",
      "%D0%A4" => "Ф",
      "%D0%A5" => "Х",
      "%D0%A6" => "Ц",
      "%D0%A7" => "Ч",
      "%D0%A8" => "Ш",
      "%D0%A9" => "Щ",
      "%D0%AA" => "Ъ",
      "%D0%AB" => "Ы",
      "%D0%AC" => "Ь",
      "%D0%AD" => "Э",
      "%D0%AE" => "Ю",
      "%D0%AF" => "Я",

      );
    
      return $st = strtr($st, $lit);
  } // -- 
    
  function translit($st) {
    $lit = array(
      "а" => "a",
      "б" => "b",
      "в" => "v",
      "г" => "g",
      "д" => "d",
      "е" => "e",
      "ё" => "yo",
      "ж" => "g",
      "з" => "z",
      "и" => "i",
      "й" => "y",
      "к" => "k",
      "л" => "l",
      "м" => "m",
      "н" => "n",
      "о" => "o",
      "п" => "p",
      "р" => "r",
      "с" => "s",
      "т" => "t",
      "у" => "u",
      "ф" => "f",
      "х" => "h",
      "ц" => "z",
      "ч" => "ch",
      "ш" => "sh",
      "щ" => "shch",
      "ъ" => "",
      "ы" => "y",
      "ь" => "",
      "э" => "e",
      "ю" => "yu",
      "я" => "ya",
 
      "А" => "A",
      "Б" => "B",
      "В" => "V",
      "Г" => "G",
      "Д" => "D",
      "Е" => "E",
      "Ё" => "Yo",
      "Ж" => "G",
      "З" => "Z",
      "И" => "I",
      "Й" => "Y",
      "К" => "K",
      "Л" => "L",
      "М" => "M",
      "Н" => "N",
      "О" => "O",
      "П" => "P",
      "Р" => "R",
      "С" => "S",
      "Т" => "T",
      "У" => "U",
      "Ф" => "F",
      "Х" => "H",
      "Ц" => "Z",
      "Ч" => "Ch",
      "Ш" => "Sh",
      "Щ" => "Shch",
      "Ъ" => "",
      "Ы" => "Y",
      "Ь" => "",
      "Э" => "E",
      "Ю" => "Yu",
      "Я" => "Ya",
    );
  return $st = strtr($st, $lit);
} // --  

    /*
     * @func   : Возвращает галереи , связанные с секцией
     * @params : section_id/section_seo_link
     * @returns: array/false/-1
     *
     */
    function getGalleriesBySection($section){
        //TODO передвинуть в модель photo
        if(is_numeric($section)){
            $q = "SELECT * FROM   sections_to_moduls  
              WHERE seo_link = '$name' "; 
            $r = mysql_query($q);
            if(!$r) return false;
            if( mysql_num_rows($r) > 0){
          
              $info = mysql_fetch_assoc($r);
              
              return $info['sm_id'] ;
            }
        } else {
        //TODO
        }
        
        return false;
    }  

    /*
     * @func   : Возвращает section_id
     * @params : section_seo_name
     * @returns: false
     *
     */
    function getSectionIdByName($name){

        $SectionsModel = new SectionsModel();
        $id = $SectionsModel->getSectionIdByName($name);

        unset($SectionsModel);

        if((int)$id > 0){
            return $id;
        }

        return false;

        /*
        $name_lower = strtolower($name);
        
        $name_spaceless = preg_replace('/_/','',$name); 
        $name_lower_spaceless = preg_replace('/_/','',$name_lower); 
    
        $q = "SELECT * FROM   sections  
              WHERE seo_link = '$name' OR title = '$name'
                    OR seo_link = '$name_lower' OR title = '$name_lower'
                    OR seo_link_translited = '$name' OR  seo_link_translited = '$name_lower'
                    OR seo_link = '$name_spaceless' OR title = '$name_spaceless' OR seo_link_translited = '$name_spaceless'
                    OR seo_link = '$name_lower_spaceless' OR title = '$name_lower_spaceless' OR seo_link_translited = '$name_lower_spaceless'
                    "; 
        $r = mysql_query($q);
        if(!$r) return false;
        if( mysql_num_rows($r) > 0){
      
          $info = mysql_fetch_assoc($r);
          
          return $info['sm_id'] ;
        } 
        
        return false;
        */
    }  
    
    /*
     * @func   :  
     * @params : int section_id
     * @returns: array $galleries/false
     *
     */
    function getGalleriesBySectionId($section_id){
        //TODO передвинуть в модель photo
        $q = "SELECT * FROM galleries WHERE sections_id = $section_id";
        $r = mysql_query($q);
        if(!$r) return false;
        if( mysql_num_rows($r) > 0){
          while($row[] = mysql_fetch_assoc($r)){
              $arr = $row;
          }
          
          
          return $arr ;
        } 
    
        return false;
    }
    
    /*
     * @func   : Достает фотки, связанные с данной секцией
     * @params : $params('modul_id', 'section_id', 'gallery_id')
     * @returns: false
     *
     */  
   function getPhotos($params){
    // [link]: ../Image/tour/photo_<gallery_id>.jpg
       //TODO передвинуть в модель photo
    
       $modul_id = '';
       $section_id = '';
       $gallery_id = ''; 

       
       $modul_id = $params['modul_id'];
       $section_id = $params['section_id'];
       $gallery_id = $params['gallery_id'];
       $modul = $this->getModulnameById($modul_id);
       
       $q = "SELECT * FROM photo WHERE modul_id = '$modul_id' 
                                    AND section_id = '$section_id'
                                    AND gallery_id = '$gallery_id'
                                    ORDER BY `sort` ASC
                                    ";
       $r = mysql_query($q);  
       if($r){     
          if( mysql_num_rows($r) > 0){
            while($row = mysql_fetch_assoc($r)){
                $tmp = $row;
                $file_name = $tmp['link'];
                $tmp['file_name'] = $file_name;
                $tmp['link'] = "../Image/$modul/{$file_name}";
                $tmp['link_sm'] = "../Image/{$modul}/sm_{$file_name}";
                $photos[] = $tmp;
            }          
          }
       }
       
       if(isset($photos))
       if(is_array($photos)){ //fb($photos);
          return $photos;
       }
       
       return false;
    }
    
    /*
     * @func   :  Собирает галереи с фотками для разделов
     * @params :  
     * @returns: false/array galleries
     *
     */
    function getGalleryBySectionId($options = null){
    
        $modul = null;
        $actionMethod = null;
        $section_seo_name = null;
        $modul_id = null;
        $section_id = null;
        $registry = Registry::getInstance();
        $gallerys = array();
   
        if(isset($options['modul'])) $modul = $options['modul'];
        if(is_null($modul ))  $modul = strtolower($registry->get('modul_index'));
        
        if(isset($options['modul_id'])) $modul_id = $options['modul_id'];
        
        if( !is_numeric($modul_id) AND isset($modul))  $modul_id = $this->getModulidByName($modul);
    
        if(isset($options['actionMethod'])){
            $actionMethod = $options['actionMethod'];
            $section_seo_name = preg_replace('/'."action". ucfirst($modul) .'/','',$actionMethod);              
        }
        
        
        if(!($section_id = $registry->get('section_id')))
            $section_id = $this->getSectionIdByName($section_seo_name);
            
        $gallerys = $this->getGalleriesBySectionId($section_id);  
        
        if($gallerys !== false)
          if(is_array($gallerys)){ 
            foreach($gallerys as $gallery){
                
                $gallery_id = $gallery['galleries_id'];
                $photos = $this->getPhotos(array('modul_id'=>$modul_id, 'section_id'=>$section_id, 'gallery_id'=>$gallery_id));  
                if(is_array($photos)) 
                  $gallery['photos'] = $photos;
                else 
                  $gallery['photos'] = -1;
                $galleries[] = $gallery;
            }     
            return $galleries;  
          }
        return false;
    }
    
    function getModulnameById($modul_id){
        $q = "SELECT * FROM moduls WHERE id_modul = $modul_id";   
        $r = mysql_query($q); 
        if($r){ 
            $row = mysql_fetch_assoc($r);
            return $row['modul_index'];
        }
        return false;
    }
    
    function getModulidByName($name){
        $q = "SELECT * FROM moduls WHERE modul_index = '$name'";
        $r = mysql_query($q); 
        if($r){ 
            $row = mysql_fetch_assoc($r);
            return $row['id_modul'];
        }
        return false;
    }
    
    function dropPhoto($photo_id){
    
        $photo = $this->getPhotoById($photo_id);  
    
        if(!is_array($photo)) return null;
    
        $file_big = SITE .  $photo['path'] . $photo['link'];
        $file_sm = SITE .  $photo['path'] . $photo['sm_link'];
  
        @unlink($file_big);
        @unlink($file_sm);
    
        $q = "DELETE FROM `photo`
                WHERE photo_id = $photo_id ";
        $r = mysql_query($q);
        if(!$r){
          return false;
        }
        
        
        
        return true;
    
    } // --
    
     
    function updatePhoto($photo){
    // TODO валидация
    
        if(!isset($photo['photo_id'])) return null;
    
        $photo_id = $photo['photo_id'];
        $title = '';
        $text = '';
        $sort = 10;
    
        if(isset($photo['title'])) $title = $photo['title'];
        if(isset($photo['text'])) $text = $photo['text'];
        if(isset($photo['sort'])) $sort = $photo['sort'];
    
         
       
        $q = "UPDATE `photo`
              SET title = '$title',
                  text = '$text',
                  sort = '$sort'
                WHERE photo_id = $photo_id "; //fb($q);
        $r = mysql_query($q);
        if(!$r){
          fb(mysql_error());
          return false;
        }
 
        return true;
    
    } // --
    
    private function getPhotoById($photo_id){
    
        
       $q = "SELECT * FROM photo WHERE photo_id = '$photo_id'  
                                    ";
       $r = mysql_query($q);  
       if($r){     
          if( mysql_num_rows($r) > 0){
            while($row = mysql_fetch_assoc($r)){
                $tmp = $row;
                $modul_index = $this->getModulnameById($row['modul_id']);
                $modul_index = strtolower($modul_index);
                $tmp['path'] = "../Image/$modul_index/";
                $tmp['sm_link'] = "sm_" . $tmp['link'];
                $photo = $tmp;
            }  
            return $photo; 
          }
       }
       
       return false;
    
    } // --
    
    function getSectionSeonameById($section_id){
        $q = "SELECT * FROM sections WHERE sm_id = $section_id"; 
        $r = mysql_query($q);  
        if($r){
          if( mysql_num_rows($r) > 0){
            $row = mysql_fetch_assoc($r);
            return $row['seo_link'];
          }
        }
        return false;
    }
    
    function insertPhoto($photo,$info){ 
        $tmp_name = $photo['name']['link']; // 6.jpg
        $tmp_type = $photo['type']['link']; // image/jpeg
        $tmp_file = $photo['tmp_name']['link']; // /tmp/php5HL2GN
        $tmp_size = $photo['size']['link']; // 195243
      
        if($tmp_file == '') return false; 
        
        $resolution = GetImageSize($photo['tmp_name']['link']);
        if($resolution[0] > 3000 OR $resolution[1] > 3000){
            //$this->message = 'resolution > 3000';
            fb('resolution > 3000');
            return false;
        }
         
        if(($file_size = $photo['size']['link']) > 2048000){
          //$this->message = 'size > 2M';
            fb('size > 2M');
             return false;
        } 
          
        if(isset($info['title'])) $title = $info['title']; else $title = '';
        if(isset($info['text'])) $text = $info['text']; else $text = '';
        if(isset($info['modul_id'])) $modul_id = $info['modul_id']; else $modul_id = 0;
        if(isset($info['parent_id'])) $parent_id = $info['parent_id']; else $parent_id = 0;
        if(isset($info['section_id'])) $section_id = $info['section_id']; else $section_id = '';
        if(isset($info['gallery_id'])) $gallery_id = $info['gallery_id']; else $gallery_id = '';
        if(isset($info['width'])) $width = $info['width']; else $width = 600;
        if(isset($info['height'])) $height = $info['height']; else $height = 300;
        if(isset($info['width_sm'])) $width_sm = $info['width_sm']; else $width_sm = 200;
        if(isset($info['height_sm'])) $height_sm = $info['height_sm']; else $height_sm = 100;
        if(isset($info['set_exact'])) $set_exact = $info['set_exact']; else $set_exact = false;
        if(isset($info['set_square'])) $set_square = $info['set_square']; else $set_square = false;
        if(isset($info['height'])) $height = $info['height']; else $height = 400;
        if(isset($info['sort'])) $sort = $info['sort']; else $sort = 10;
        if(isset($info['modul'])) $modul = $info['modul']; else $modul = $this->getModulnameById($modul_id);
       
        //TODO
        if($set_exact){}
        if($set_square){}
        //
         
        
        $new_photo_id = $this->getCountPhoto( array('modul_id'=>$modul_id,'section_id'=>$section_id,'gallery_id'=>$gallery_id) );  
        $new_photo_id ++; 
        
        $rnd_val = md5(rand() . date("H:i:s")); 
        $rnd_val = substr($rnd_val,0,8);
        
        $link = "{$section_id}_{$gallery_id}_{$rnd_val}.jpg";
        $link_sm = "sm_$link";
        
        $q = "INSERT INTO `photo` SET `parent_id` = '$parent_id',
                                      `modul_id` = '$modul_id',
                                      `section_id` = '$section_id',
                                      `gallery_id` = '$gallery_id',
                                      `date_added` = NOW(),
                                      `title` = '$title',
                                      `text` = '$text',
                                      `link` = '$link',
                                      `sort` = '$sort'
                                      ";
                                      
        $q = mysql_query($q);
        if(!$q) { fb( mysql_error() ); }  
        
        $photo_id = mysql_insert_id();
        
        //
        $file = SITE . "../Image/$modul/$link";
        $file_sm = SITE . "../Image/$modul/$link_sm";
        
        //fb($_FILES); //  
        //fb($file); // /home/babagayr/public_html/blagovist.com.ua../Image/tour/photo_1_6.jpg
        //copy($tmp_file,$file);
        $this->imgCropAndResize($tmp_file,$file,$width);
        $this->imgCropAndResize($tmp_file,$file_sm,$width_sm);
    }
    
    private function getCountPhoto($options = null){ 
        
        if(isset($options['modul_id'])) $modul_id = $options['modul_id']; else $modul_id = 0;
        if(isset($options['section_id'])) $section_id = $options['section_id']; else $section_id = 0;
        if(isset($options['gallery_id'])) $gallery_id = $options['gallery_id']; else $gallery_id = 0;
    
        $q = "SELECT COUNT('photo_id') count FROM `photo`
                WHERE modul_id = $modul_id
                AND section_id = $section_id
                AND gallery_id = $gallery_id ";
        $r = mysql_query($q);
        if($r){
          if( mysql_num_rows($r) > 0){
            $row = mysql_fetch_assoc($r);
            return $row['count'];
          }  
        }
        return false;
    }

    function getColModel($modul, $filename, $root = null){
        $reader = new Zend\Config\Reader\Xml();
        $data   = $reader->fromFile(SITE. "/Moduls/$modul/$filename.xml");

        if(!is_null($root)){
            if(isset($data[$root])) $data = $data[$root];
        }

        unset ($reader);

        return $data;

    }

    function getXml($filename, $root = null){
        $reader = new Zend\Config\Reader\Xml();
        $data   = $reader->fromFile(SITE. "/templates/xml.$filename.xml");

        /*
        $obj = new stdClass();
        $obj->data = $data;

        return $obj;
        */

        if(!is_null($root)){
            if(isset($data[$root])) $data = $data[$root];
        }

        unset ($reader);

        return $data;
    }

    /*
     * рекурсиваня формализация xml-массива меню
     * Приведение к виду $menu_arr['group'][0]['item'][2]['param'][0]['key']
     * [!] item должен обязательно иметь атрибуты href, name = "имя [виртуального] модуля"
     */
    function xmlMenuArrFormat( $xml_arr){

        // Защита от зацикливания
        $this->index++;
        if($this->index == 50) return $xml_arr;

        if( is_null($this->unit) ){
            $this->unit = $this->registry->request->get(1);
        }


        $result = array();


        if( isset($xml_arr['href']) ){
            // Это лист дерева меню (<item>)

            $item_name = isset($xml_arr['name']) ? $xml_arr['name'] : '';
            if( $item_name ==  $this->unit OR $item_name ==   $this->unit ){
                // Если текущий [виртуальный] модуль совпадает с названием айтема, подсветить его
                $xml_arr['class'] = 'active';
            }

            if( !isset($xml_arr['param']) ){
                // Если нет массива param
                $this->stop_xml_forming = true;
                return $xml_arr;
            } else {
                $xml_arr['param'] = $this->xmlMenuArrFormat($xml_arr['param']);
                return $xml_arr;
            }
        }

        if( !is_array($xml_arr)  ){
            $this->stop_xml_forming = true;
            return $xml_arr;
        }

        foreach($xml_arr as $key => $item){
            if(isset($item[0])){
                $result[$key] = $item;

                if( is_array($item) AND $this->stop_xml_forming === false ){
                    // Надо ли продолжать рекурсию
                    for($t=0; $t<count($item); $t++){
                        $result[$key][$t] = $this->xmlMenuArrFormat($item[$t]);
                    }
                }

            } else {

                if( is_array($item) AND $this->stop_xml_forming === false ){
                    // Надо ли продолжать рекурсию
                    $result[$key][] = $this->xmlMenuArrFormat($item);

                } else {
                    $result[$key][] = $item;
                    return $result;
                }

            }
        }



        return $result;

    }

    /*
     * Заливает картинку сначала на сервер, а потом на ftp
     */
    function uploadImage($filename, $unit){


        $local_path = "tmp/";

        $adapter = new Upload(     array('remote_folder' => $unit,
                                'remote_root_dir' => REMOTE_SITE_DIR,
                                'local_path' => $local_path,
                                'local_file' => $filename,
                                        )  );

        $adapter->addFilter('File\Rename',array(
            'source' => $_FILES['photo']['tmp_name'],
            'target' => $local_path.$filename,
            'overwrite' => true
        ));

        $adapter
            ->addValidator('Count', false, 1)

            ->addValidator('Extension',
            false,
            array('extension1' => 'jpg,jpeg,jpf,png,gif,bmp,JPG,JPEG,PNG',
                'case' => true))

            ->addValidator('FilesSize',
            false,
            array('min' => 100,
                'max' => 4500000, //1M
                'bytestring' => true))

        //        ->addValidator('Size', false, array('max' => '5242880'))

            ->addValidator('ImageSize',
            false,
            array('minwidth' => 10,
                'minheight' => 10,
                'maxwidth' => 3500,
                'maxheight' => 3500));


        $adapter->receive();

        $r = (bool)$adapter->isReceived();

        unset($adapter);

        return $r;
    }

    /*
     * Массив столбцов для гриды
     */
    function getColumnModel($modul = null, $filename = null, $root = null){

        if(is_null($modul)) $modul = Registry::getInstance() -> modul;
        //if(is_null($filename)) $filename = Registry::getInstance() -> grid_name;
        //if(is_null($root)) if(!is_null($this->root)) $root = $this->root;

        if(is_null($filename)) return false;

        $reader = new Zend\Config\Reader\Xml();
        $data   = $reader->fromFile(SITE. "/Moduls/$modul/$filename.xml");

        if(!is_null($root)){
            if(isset($data[$root])) $data = $data[$root];
        } else {
            if(isset($data[$filename.'_grid']['column'])) $data = $data[$filename.'_grid']['column'];
        }

        unset ($reader);

        return $data;
    }


    function openFtpConnection(){
        $host = FTP_HOST;
        $usr = FTP_USER;
        $pwd = FTP_PASS;
        $site_root = FTP_FRONTEND;

        $result = false;

        $ftpConnection = @ftp_connect($host);

        $login_result = @ftp_login($ftpConnection, $usr, $pwd);

        if((bool)$login_result === true){
            $this->ftpConnection = $ftpConnection;
            ftp_pasv($this->ftpConnection, true);
            $result = true;
        }

        return $result;
    }

    function getFtpConnection(){
        return $this->ftpConnection;
    }

    function setFtpConnection($ftpConnection){
        return $this->ftpConnection = $ftpConnection;
    }

    function closeFtpConnection(){
         $this->ftpConnection = null;
    }

    /*
     *  функция записи в файл по ftp
     */
    function putRemoteFile($file, $local_path = null, $ftp_path = null, $unit = null, $persistent = false){

        $host = FTP_HOST;
        $usr = FTP_USER;
        $pwd = FTP_PASS;
        $site_root = FTP_FRONTEND;

        if(is_null($ftp_path))   $ftp_path = "public_html/$site_root/Image/$unit";


        //$file = 'test.php';
        //'public_html/'. $this->remote_root_dir .'/Image/' .  $this->remote_folder . "/" . 'sm_' . $this->local_file


        //$str ="replace all contenents"; // /public_html/remontik.kh.ua/Image
        //$ftpConnection = "ftp://$usr:$pwd@$host/{$ftp_path}";
        //$ftpConnection = "ftp://$usr:$pwd@$host";

        $ftpConnection = $this->ftpConnection;

        if(is_null($this->ftpConnection) AND (bool)$persistent === false){
            $ftpConnection = @ftp_connect($host);

            $login_result = @ftp_login($ftpConnection, $usr, $pwd);

            ftp_pasv($ftpConnection, true);
        }


        //$opts = array('ftp' => array('overwrite' => true));

        //$ftpPath =

        //$context = stream_context_create($opts);
        //$root = ftp_pwd($ftpConnection);

        ftp_chdir($ftpConnection, "/");


        $is_dir = @ftp_chdir($ftpConnection, $ftp_path);


        if( (bool)$is_dir === false ){
            ftp_mkdir($ftpConnection,$ftp_path);
        }

        clearstatcache();
        $is_local_file = file_exists($local_path."/".$file);

        ftp_chdir($ftpConnection, "/".$ftp_path);

        if((int) $is_local_file === 1){
            //ftp_nb_put($ftpConnection, $ftp_path, $local_path, FTP_BINARY);
            ftp_put($ftpConnection, $file, $local_path."/".$file, FTP_BINARY);

        }


        //@ftp_put($ftpConnection, $ftp_path, $local_path, FTP_BINARY);


        if((bool)$persistent === false)        @ftp_close($ftpConnection);

        //$strwri = file_put_contents($ftpConnection,$str,0,$context);
    }

    function delRemoteFile($remote_file, $remote_folder){
        //TODO

        $host = FTP_HOST;
        $usr = FTP_USER;
        $pwd = FTP_PASS;
        $site_root = FTP_FRONTEND;

        $result = -1;

        $file = "public_html/$site_root/Image/$remote_folder/$remote_file";

        // установка соединения
        $ftpConnection = @ftp_connect($host);


        ftp_pasv($ftpConnection, true);

        if ($ftpConnection) {
            // вход с именем пользователя и паролем
            $login_result = @ftp_login($ftpConnection, $usr, $pwd);

            if($login_result){

                try {
                    // попытка удалить файл
                    if (@ftp_delete($ftpConnection, $file)) {
                        $result = true;
                        fb( "Файл $file удален");
                    } else {
                        $result = false;
                        fb( "Не удалось удалить $file");
                    }
                } catch(Exception $e){
                    //TODO запись в лог
                    //asdr("Model::delRemoteFile() " . $e->getMessage());
                }


            }

            // закрытие соединения
            @ftp_close($ftpConnection);
        }

        return $result;

        /*
         *



                $uploadFilename = $filename;
                $uploadFilename = str_replace( $this->local_path, '', $filename);
                //$uploadFilename = str_replace(IMAGES_PATH, '', $filename);
                //$uploadFilename = str_replace('./public/images/', '', $uploadFilename);

                $localFilename = $filename;



                $ftpPath = 'public_html/'. $this->remote_root_dir .'/Image/' .  $this->remote_folder . "/" . $uploadFilename;

                $ftpConnection = @ftp_connect($host);
                if ($ftpConnection) {

                    $ftpLogin = @ftp_login($ftpConnection, $usr, $pwd);
                    if ($ftpLogin) {
                        @ftp_put($ftpConnection, $ftpPath, $localFilename, FTP_BINARY);

                        $sm_file = PUBLIC_PATH . "/tmp/sm_" . $this->local_file  ; ///fb($sm_file);
                        if( file_exists($sm_file) ){
                            @ftp_put( $ftpConnection,
                                $ftpPath = 'public_html/'. $this->remote_root_dir .'/Image/' .  $this->remote_folder . "/" . 'sm_' . $this->local_file,
                                $localFilename = $sm_file,
                                FTP_BINARY
                            );
                        }
                    }
                    @ftp_close($ftpConnection);
                }
         */

        /*
         *
         */
    }

    function fileupload($file){

        $filename = $this->registry->request->getParam('qqfile');
        $multisave_arr = array();

        $input = fopen("php://input", "r");
        $temp = tmpfile();
        $realSize = stream_copy_to_stream($input, $temp);
        fclose($input);
        if(!isset($_SERVER["CONTENT_LENGTH"]) || $realSize != (int)$_SERVER["CONTENT_LENGTH"]) return array('status'=>'err','msg'=>'The actual size of the file does not match the passed');

        if(is_dir($file)) {
            ///$_GET['qqfile'] = explode('\\',$_GET['qqfile']);
            ///$_GET['qqfile'] = array_pop($_GET['qqfile']);
            ///$file = $file.'/'.$_GET['qqfile'];
            $file = $file . "/" . $filename;
        }

        $target = fopen($file, "w");
        fseek($temp, 0, SEEK_SET);
        stream_copy_to_stream($temp, $target);
        fclose($target);

        #
        if(isset($_SESSION['multisave_arr'])) $multisave_arr = $_SESSION['multisave_arr'];

        $multisave_arr[] = $file;

        $_SESSION['multisave_arr'] = $multisave_arr;

        #
        return $filename;
    }

    /*
     * Converts obj to array
     */
    function dismount($object) {
        $reflectionClass = new ReflectionClass(get_class($object));
        $array = array();
        foreach ($reflectionClass->getProperties() as $property) {
            $property->setAccessible(true);
            $array[$property->getName()] = $property->getValue($object);
            $property->setAccessible(false);
        }
        return $array;
    }

    
} //-- class

interface BasicModelInterface {
      //function render();
} // --

class BasicModulModel extends Model {
// Дополнительный класс-прослойка, от которого наследуются модели модулей
} // --

  

?>